import React, { useState, useEffect, useRef } from 'react';
import { Form, Button, Input, Affix, Select, message, Space, Switch, Drawer, Row, Col, Modal } from 'antd';
import { MinusCircleOutlined, PlusCircleOutlined } from '@ant-design/icons';
import { useModelAssociateType } from '@/components';
import cmdbres from '@/data/cmdbres';
import hcpiam from '@/data/hcpiam';
import request, { requestIAM } from '@/utils/request';
import regexpUtil from '@/utils/regexpUtil';
import hcpUtils from '@/utils/hcpUtils';
import RelationTable from './relationTable';

const user = hcpUtils.getUser();
const CreateRelation = ({
    history,
    visible,
    setVisible,
    onCreateFinish,
    cmModuleId,
    moduleInfo,
    cmInfo,
    getTableData,
}) => {
    const [form] = Form.useForm();
    const [{ associateType }] = useModelAssociateType();
    const [modelAssociateData, setModelAssociateData] = useState([]);

    const queryModelAssociateData = async () => {
        try {
            const resSrc = await request({
                ...cmdbres.queryAllModelAssociate,
                data: {
                    srcModuleId: cmModuleId,
                },
            });
            const resDesc = await request({
                ...cmdbres.queryAllModelAssociate,
                data: {
                    destModuleId: cmModuleId,
                },
            });

            Promise.all([resSrc, resDesc])
                .then((result) => {
                    let arr = [];
                    result?.map((item) => {
                        if (item.data) {
                            item?.data?.map((c) => {
                                const isDest = c.destModuleId == cmModuleId;
                                if (isDest) {
                                    arr.push({
                                        ...c,
                                        displayModuleCode: c.srcModuleCode,
                                        displayModuleId: c.srcModuleId,
                                        displayModuleName: c.srcModuleName,
                                        isDest,
                                    });
                                } else {
                                    arr.push({
                                        ...c,
                                        displayModuleCode: c.destModuleCode,
                                        displayModuleId: c.destModuleId,
                                        displayModuleName: c.destModuleName,
                                        isDest,
                                    });
                                }
                            });
                        }
                    });
                    setModelAssociateData(arr);
                    if (arr.length) {
                        form.setFieldsValue({
                            destModule: arr[0].displayModuleId,
                        });
                        setDescModule(arr[0]);
                    }
                })
                .catch((error) => {
                    console.log(error);
                });
        } catch (error) {
            console.log(error);
        }
    };

    useEffect(() => {
        queryModelAssociateData();
    }, []);

    const [descModule, setDescModule] = useState();
    const changeDestModule = (value, option) => {
        setDescModule(option.data);
    };

    const handleClose = () => {
        setVisible(false);
    };

    return (
        <Modal
            title="新增关联"
            className="hcp-modal-md create-field"
            width={600}
            visible={visible}
            footer={null}
            onCancel={handleClose}
            destroyOnClose
            maskClosable={false}
            afterClose={() => {
                form.resetFields();
            }}
        >
            <Form form={form} name="basic">
                <Form.Item
                    label="关联列表"
                    name="destModule"
                    key="destModule"
                    rules={[{ required: true, message: '请选择' }]}
                    style={{ marginBottom: 0 }}
                >
                    <Select
                        placeholder="请选择"
                        style={{ width: '100%', marginRight: 10, marginBottom: 10 }}
                        onChange={changeDestModule}
                        showSearch
                    >
                        {modelAssociateData?.map((item, index) => (
                            <Select.Option key={item.displayModuleCode} value={item.displayModuleId} data={item}>
                                {associateType?.[item.associateType]}-{item.displayModuleName}
                            </Select.Option>
                        ))}
                    </Select>
                </Form.Item>
            </Form>
            <RelationTable
                srcModule={moduleInfo}
                cmInfo={cmInfo}
                destModule={descModule}
                onRelationFinish={() => {
                    getTableData();
                }}
            />

            <div className="hcp-modal-body-footer">
                <Form.Item wrapperCol={{ span: 24 }}>
                    <Button onClick={handleClose}>取消</Button>
                    <Button type="primary" onClick={handleClose}>
                        确认
                    </Button>
                </Form.Item>
            </div>
        </Modal>
    );
};

export default CreateRelation;
